let wxpay = require('../../utils/pay.js')
let app = getApp()
let NORMAL = 0, LOWER = 1, PULLDOWN = 2
Page({
  data:{
    statusType: ["全部", "待付款", "待发货", "待收货", "已完成"],
    statusStr: { '0': '待发货', '1': '已发货', '2': '已完成', '3': '已评价'},
    payStatusStr: { '0': '待付款', '3': "已关闭"},
    currentType: 0,
    tabClass: ["", "", "", "", ""],
    orderList: [],
    imgUrl: app.globalData.imgUrl,
    offset: 1,
    limit: 10,
    loading: false,
    loadingComplete: false,
    loaded: false,
    noConnect: false,
  },
  statusTap: function(e){
     var curType =  e.currentTarget.dataset.index;
     //this.data.currentType = curType
     this.setData({
       orderList: [],
       currentType: curType
     });

    this.setData({
      offset: 1,
      limit: 10,
      loading: false,
      loadingComplete: false,
      loaded: false,
      noConnect: false,
    })

     this.onShow();
  },
  orderDetail : function (e) {
    let index = e.currentTarget.dataset.index
    let orderTemp = this.data.orderList[index]
    orderTemp.statusStr = orderTemp.orderinfo.pay_status == 0 ? this.data.payStatusStr[orderTemp.orderinfo.status] : this.data.statusStr[orderTemp.orderinfo.status]

    wx.navigateTo({
      url: "/pages/order-details/index?order=" + JSON.stringify(orderTemp)
    })
  },
  
  onLoad:function(e){
    // 生命周期函数--监听页面加载
    this.setData({
      currentType: e.type
    })

    //this.onShow()
   
  },
  onReady:function(){
    // 生命周期函数--监听页面初次渲染完成
 
  },
  
  onShow:function(){
    this.getDataList(this.data.currentType, NORMAL)
  },
  onHide:function(){
    // 生命周期函数--监听页面隐藏
 
  },
  onUnload:function(){
    // 生命周期函数--监听页面卸载
  },
  onPullDownRefresh: function() {
    // 页面相关事件处理函数--监听用户下拉动作
   
  },
  // onReachBottom: function() {
  //   // 页面上拉触底事件的处理函数
  
  // },
  /**
   * 
   */
  getDataList: function (type, flag) {
    if (type == 0) {
      this.getOrderList(0, 6, flag)
    } else if (type == 1) {
      this.getOrderList(0, 0, flag)
    } else if (type == 2) {
      this.getOrderList(1, 0, flag)
    } else if (type == 3) {
      this.getOrderList(1, 1, flag)
    } else {
      this.getOrderList(1, 2, flag)
    }
  },
  /**
   * 跳转至评价页面
   */
  toJudgeList: function (e) {
    let index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: "/pages/judge-list/index?productlist=" + JSON.stringify(this.data.orderList[index].orderitem)
    })
  },

  /**
   * 获取订单列表
   */
  getOrderList: function (payStatus, status, flag) {
    let token = wx.getStorageSync('token')
    let that = this

    if (flag == LOWER) {
      this.setData({
        loading: true,
      })
    }

    wx.request({
      url: app.apiUrl('/order/index'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        pay_status: payStatus,
        status: status,
        page: that.data.offset,
        page_size: that.data.limit
      },
      success: function (res) {
        console.log('getOrderList')
        console.log(res.data)
        let orderListTemp = []
        let loadingComplete = false
        if (res.data.code > app.globalData.successCode) {

          if (res.data.code != 19001) {
            wx.showToast({
              title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
              icon: 'none',
              duration: 2000
            })    
          } else {
            loadingComplete = true
          }

          that.setData({
            orderList: [],
            loaded: true,
          })
          
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          if (!(res.data.data.length == that.data.limit)) {
            loadingComplete = true
          }

          orderListTemp = res.data.data

          that.setData({
            orderList: flag == LOWER ? that.data.orderList.concat(orderListTemp) : orderListTemp,
            loadingComplete: loadingComplete
          })
        }

        that.setData({
      
          loadingComplete: loadingComplete
        })
  
      },
      fail: function (res) {
        that.setData({
          noConnect: true
        })
        // wx.showModal({
        //   title: '提示',
        //   content: '网络请求异常',
        //   showCancel: false
        // })
      },
      complete: function (res) {
        that.setData({
          loaded: true
        })
        if (flag == LOWER) {
          that.setData({
            loading: false,
          })
        } else if (flag == PULLDOWN) {
          wx.hideNavigationBarLoading() //完成停止加载
          wx.stopPullDownRefresh() //停止下拉刷新
        }
      }
    })
  },
  /**
   * 取消订单
   */
  cancel: function (e) {
    let id = e.currentTarget.dataset.id
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/order/cancel'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        id: id
      },
      success: function (res) {
        console.log(res.data.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          wx.showToast({
            title: '订单已取消',
            icon: 'none',
            duration: 2000
          })
          that.onShow()
        }

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },
  /**
   * 未支付订单付款 
   */
  pay: function (e) {
    let index = e.currentTarget.dataset.index
    let order = this.data.orderList[index]
    wx.navigateTo({
      url: "/pages/pay-select/index?orderid=" + order.orderinfo.id + "&money=" + order.orderinfo.total_price_pay + "&createtime=" + order.orderinfo.created_at + "&fromID=1"
    })
  },

  /**
   * 确认是否确认收货
   */
  confirmRecept: function (e) {
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否确认收到商品？',
      cancelText: '取消',
      confirmText: '确定',
      success: function (res) {
        if (res.confirm) {
          that.confirm(e)
        }
      }
    })
  },

  /**
   * 确认收货
   */
  confirm: function (e) {
    let id = e.currentTarget.dataset.id
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/order/finish'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        id: id
      },
      success: function (res) {
        console.log(res.data.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          wx.showToast({
            title: '确认收货成功',
            icon: 'none',
            duration: 2000
          })
          that.onShow()
        }

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },
  /**
   * 售后
   */
  toServiceList: function (e) {
    let index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: "/pages/to-service-list/index?productlist=" + JSON.stringify(this.data.orderList[index].orderitem)
    })
  },
  /**
   * 查看物流
   */
  toLogicticsDetails: function (e) {
    let that = this
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "/pages/logictics-details/index?id=" + id
    })
  },
  /**
  * 下拉刷新  
  */
  onPullDownRefresh: function () {
    this.data.offset = 1
    this.setData({
      loading: false,
      loadingComplete: false,
      loaded: false,
      noConnect: false,

    })
    this.data.list = []
    wx.showNavigationBarLoading()
    this.getDataList(this.data.currentType, PULLDOWN)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("toLower" + this.data.loadingComplete)
    this.setData({
      loading: this.data.loading,
      loadingComplete: this.data.loadingComplete
    })
    if (!this.data.loadingComplete) {
      this.data.offset += 1
      this.getDataList(this.data.currentType, LOWER)
    }
  }

})
